<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="工单ID" prop="orderId">
        <el-input
            v-model="queryParams.orderId"
            placeholder="请输入工单ID"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="检验项目ID" prop="itemId">
        <el-input
            v-model="queryParams.itemId"
            placeholder="请输入检验项目ID"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="样本序号" prop="sampleIndex">
        <el-input
            v-model="queryParams.sampleIndex"
            placeholder="请输入样本序号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单项判定结果" prop="result">
        <el-input
            v-model="queryParams.result"
            placeholder="请输入单项判定结果"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['quality-service:results:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['quality-service:results:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['quality-service:results:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['quality-service:results:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="resultsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="检验结果ID" align="center" prop="resultId" />
      <el-table-column label="工单ID" align="center" prop="orderId" />
      <el-table-column label="检验项目ID" align="center" prop="itemId" />
      <el-table-column label="样本序号" align="center" prop="sampleIndex" />
      <el-table-column label="详细描述" align="center" prop="defectDescription" />
      <el-table-column label="图片" align="center" width="180">
        <template #default="scope">
          <el-link
              type="primary"
              @click="handlePreview(scope.row)"
              v-if="scope.row.imageUrls && scope.row.imageUrls.length"
          >
            查看图片({{ scope.row.imageUrls.length }}张)
          </el-link>
          <span v-else>无图片</span>
        </template>
      </el-table-column>
      <el-table-column label="检验执行人员ID" align="center" prop="inspectorId" />
      <el-table-column label="检验执行时间" align="center" prop="inspectionTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.inspectionTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['quality-service:results:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['quality-service:results:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 图片预览弹窗 -->
    <el-dialog
        v-model="previewVisible"
        title="图片预览"
        width="60%"
        append-to-body
        :close-on-click-modal="false"
    >
      <div style="text-align: center; position: relative; min-height: 300px;">
        <el-icon
            class="nav-arrow left-arrow"
            @click="prevImage"
            v-show="currentImageIndex > 0"
        >
          <ArrowLeft />
        </el-icon>

        <el-image
            :src="currentImageUrl"
            fit="contain"
            style="max-height: 70vh;"
            :preview-src-list="currentImageList"
            :initial-index="currentImageIndex"
            hide-on-click-modal
        >
          <template #error>
            <div class="image-error">
              <el-icon><Picture /></el-icon>
              <span>图片加载失败</span>
            </div>
          </template>
        </el-image>

        <el-icon
            class="nav-arrow right-arrow"
            @click="nextImage"
            v-show="currentImageIndex < currentImageList.length - 1"
        >
          <ArrowRight />
        </el-icon>

        <div class="image-counter" v-if="currentImageList.length > 1">
          {{ currentImageIndex + 1 }} / {{ currentImageList.length }}
        </div>
      </div>

      <template #footer>
        <el-button @click="previewVisible = false">关闭</el-button>
      </template>
    </el-dialog>


    <!-- 在表格后面添加图表组件 -->
    <pass-rate-chart
        :results-data="resultsList"
        :auto-refresh="true"
        :refresh-interval="30"
    />


    <!-- 添加/编辑对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="resultsRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="工单ID" prop="orderId">
          <el-input v-model="form.orderId" placeholder="请输入工单ID" />
        </el-form-item>
        <el-form-item label="检验项目ID" prop="itemId">
          <el-input v-model="form.itemId" placeholder="请输入检验项目ID" />
        </el-form-item>
        <el-form-item label="样本序号" prop="sampleIndex">
          <el-input v-model="form.sampleIndex" placeholder="请输入样本序号" />
        </el-form-item>
        <el-form-item label="详细描述" prop="defectDescription">
          <el-input v-model="form.defectDescription" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="图片上传">
          <el-upload
              action="#"
              list-type="picture-card"
              :auto-upload="false"
              :on-change="handleFileChange"
              :on-remove="handleRemove"
              :file-list="form.fileList"
              multiple
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="检验执行人员ID" prop="inspectorId">
          <el-input v-model="form.inspectorId" placeholder="请输入检验执行人员ID" />
        </el-form-item>
        <el-form-item label="检验执行时间" prop="inspectionTime">
          <el-date-picker
              v-model="form.inspectionTime"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择检验执行时间"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { listResults, getResults, delResults, addResults, updateResults } from "@/api/quality-service/results"
import { Picture, ArrowLeft, ArrowRight } from '@element-plus/icons-vue'
import PassRateChart from "@/views/quality-service/results/PassRateChart.vue";
const { proxy } = getCurrentInstance()

// 数据状态
const resultsList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// 图片预览相关
const previewVisible = ref(false)
const currentImageList = ref([])
const currentImageIndex = ref(0)
const currentImageUrl = ref('')

const data = reactive({
  form: {
    fileList: []
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderId: null,
    itemId: null,
    sampleIndex: null,
    defectDescription: null,
    inspectorId: null,
    inspectionTime: null
  },
  rules: {
    orderId: [{ required: true, message: "工单ID不能为空", trigger: "blur" }],
    itemId: [{ required: true, message: "检验项目ID不能为空", trigger: "blur" }],
    sampleIndex: [{ required: true, message: "样本序号不能为空", trigger: "blur" }],
    inspectorId: [{ required: true, message: "检验执行人员ID不能为空", trigger: "blur" }],
    inspectionTime: [{ required: true, message: "检验执行时间不能为空", trigger: "blur" }]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询列表 */
function getList() {
  loading.value = true
  listResults(queryParams.value).then(response => {
    resultsList.value = response.rows.map(item => ({
      ...item,
      // 将图片URL字符串转为数组
      imageUrls: item.defectImageUrl ? item.defectImageUrl.split(',') : []
    }))
    total.value = response.total
    loading.value = false
  })
}

// 图片预览处理
function handlePreview(row) {
  currentImageList.value = row.imageUrls || []
  currentImageIndex.value = 0
  currentImageUrl.value = currentImageList.value[0] || ''
  previewVisible.value = true
}

// 上一张图片
function prevImage() {
  if (currentImageIndex.value > 0) {
    currentImageIndex.value--
    currentImageUrl.value = currentImageList.value[currentImageIndex.value]
  }
}

// 下一张图片
function nextImage() {
  if (currentImageIndex.value < currentImageList.value.length - 1) {
    currentImageIndex.value++
    currentImageUrl.value = currentImageList.value[currentImageIndex.value]
  }
}

// 文件上传处理
function handleFileChange(file, fileList) {
  form.value.fileList = fileList
}

// 文件移除处理
function handleRemove(file, fileList) {
  form.value.fileList = fileList
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    resultId: null,
    orderId: null,
    itemId: null,
    sampleIndex: null,
    defectDescription: null,
    fileList: [],
    inspectorId: null,
    inspectionTime: null
  }
  proxy.resetForm("resultsRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.resultId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加质量检验结果"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _resultId = row.resultId || ids.value
  getResults(_resultId).then(response => {
    form.value = {
      ...response.data,
      fileList: response.data.defectImageUrl
          ? response.data.defectImageUrl.split(',').map(url => ({ url }))
          : []
    }
    open.value = true
    title.value = "修改质量检验结果"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["resultsRef"].validate(valid => {
    if (valid) {
      // 处理图片数据
      const imageUrls = form.value.fileList.map(file => file.url || file.response?.url)
      const submitData = {
        ...form.value,
        defectImageUrl: imageUrls.join(',')
      }

      if (form.value.resultId != null) {
        updateResults(submitData).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addResults(submitData).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _resultIds = row.resultId || ids.value
  proxy.$modal.confirm('是否确认删除质量检验结果编号为"' + _resultIds + '"的数据项？').then(function() {
    return delResults(_resultIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('quality-service/results/export', {
    ...queryParams.value
  }, `results_${new Date().getTime()}.xlsx`)
}

// 初始化
onMounted(() => {
  getList()
})
</script>

<style scoped>
.image-preview-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.nav-arrow {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  font-size: 24px;
  cursor: pointer;
  color: #fff;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  padding: 8px;
  z-index: 10;
}

.left-arrow {
  left: 20px;
}

.right-arrow {
  right: 20px;
}

.image-counter {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(0, 0, 0, 0.5);
  color: white;
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 14px;
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: var(--el-text-color-secondary);
}

.image-error .el-icon {
  font-size: 50px;
  margin-bottom: 10px;
}
</style>